<template>
    <div class="external-service-page">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
           
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error">
            加载失败：{{ error }}
        </div>

        <!-- 数据展示 -->
        <div v-else class="data-container">
            <div class="content-container">
                <!-- 查询表单 -->
                <div class="search-form-wrapper">
                    <el-form :inline="true" :model="searchForm" class="search-form">
                        <el-row :gutter="20">
                            <!-- 动态渲染表单字段 -->
                            <el-col :span="6" v-for="field in searchFormConfig" :key="field.queryAttributName">
                                <el-form-item :label="field.queryAttributLabel">
                                    <!-- 根据字段类型渲染不同的组件 -->
                                    <el-input v-if="field.queryAttributType === 'input'" v-model="searchForm[field.queryAttributName]"
                                        :placeholder="field.queryAttributPlaceholder" clearable />
                                    <el-date-picker v-else-if="field.queryAttributType === 'date-picker'"
                                        v-model="searchForm[field.queryAttributName]" type="date" :placeholder="field.queryAttributPlaceholder"
                                        clearable />
                                    <el-select v-else-if="field.queryAttributType === 'select'" v-model="searchForm[field.queryAttributName]"
                                        :placeholder="field.queryAttributPlaceholder" clearable>
                                        <el-option v-for="option in field.options" :key="option.value"
                                            :label="option.label" :value="option.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <!-- 按钮组 -->
                            <el-col :span="6">
                                <el-form-item>
                                    <el-button type="primary" @click="search">查询</el-button>
                                    <el-button @click="reset">重置</el-button>
                                    <el-button class="toggle-btn" :class="{ hovered: isHovered }"
                                        @mouseenter="isHovered = true" @mouseleave="isHovered = false"
                                        @click="toggleAdvancedSearch">
                                        <span>{{ isAdvancedSearch ? "收起" : "展开" }}</span>
                                        <el-icon>
                                            <ArrowUp v-if="isAdvancedSearch" />
                                            <ArrowDown v-else />
                                        </el-icon>
                                    </el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <!-- 隐藏查询条件 -->
                        <el-row v-if="isAdvancedSearch" :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="日期">
                                    <el-date-picker
                                        v-model="searchForm.date"
                                        type="date"
                                        placeholder="选择日期"
                                        clearable
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <!-- 表格区域 -->
                <div class="table-container">
                    <el-table :data="tableData" :border="true" stripe style="width: 100%; height: 100%"
                        :row-class-name="tableRowClassName">
                        <el-table-column prop="date" label="日期" width="180" />
                        <el-table-column prop="name" label="姓名" width="180" />
                        <el-table-column prop="address" label="地址" />
                    </el-table>
                </div>
                <!-- 分页 -->
                <div class="pagination-wrapper">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                        :total="total" @current-change="fetchData" @size-change="fetchData" />
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

// 定义数据类型
interface TableData {
    date: string;
    name: string;
    address: string;
}

// 数据状态
const tableData = ref<TableData[]>([]);
const loading = ref<boolean>(true);
const error = ref<string | null>(null);

// 标志变量，用于标记是否已经初始化
const isInitialized = ref<boolean>(false);

// 访问外部服务进行初始化
const executeInitWhenFirstLoaded = async () => {
    // 如果已经初始化，直接返回
    if (isInitialized.value) {
        return;
    }

    try {
        // 发送 HTTP 请求
        const response = await axios.get(
            "/mock/api/web-display/main-display/getDisplayInfo"
        );
        if (response.data.result === true) {
            // 动态获取 SearchForm 信息
            // 动态获取 TableForm 信息
            console.info(response);
            // 假设 response.data.data 是表格数据
            tableData.value = response.data.data || [];
        } else {
            error.value = response.data.msg || "请求失败，未知错误";
        }
    } catch (err) {
        error.value = (err as Error).message || '未知错误';
    } finally {
        loading.value = false; // 无论成功或失败，都关闭加载状态
        isInitialized.value = true; // 标记为已初始化
    }
};

// 页面加载时自动调用
onMounted(() => {
    executeInitWhenFirstLoaded();
});

// 查询表单属性定义
interface SearchFormFieldDefinition {
    queryAttributName: string; // 查询属性名称
    queryAttributLabel: string; // 查询属性标签
    queryAttributType: string; // 查询属性类型
    queryAttributPlaceholder?: string; // 查询属性提示信息
    options?: { label: string; value: any }[]; // 下拉框选项
}

// 表单配置
const searchFormConfig = ref<SearchFormFieldDefinition[]>([
    {
        queryAttributType: 'input',
        queryAttributLabel: '姓名',
        queryAttributName: 'name',
        queryAttributPlaceholder: '请输入姓名',
    },
    {
        queryAttributType: 'input',
        queryAttributLabel: '地址',
        queryAttributName: 'address',
        queryAttributPlaceholder: '请输入地址',
    },
    {
        queryAttributType: 'date-picker',
        queryAttributLabel: '日期',
        queryAttributName: 'date',
        queryAttributPlaceholder: '选择日期',
    },
    {
        queryAttributType: 'select',
        queryAttributLabel: '城市',
        queryAttributName: 'city',
        queryAttributPlaceholder: '请选择城市',
        options: [
            { label: '北京', value: 'Beijing' },
            { label: '上海', value: 'Shanghai' },
            { label: '广州', value: 'Guangzhou' },
            { label: '深圳', value: 'Shenzhen' },
        ],
    },
]);

// 查询表单数据
const searchForm = ref<Record<string, any>>({});

// 初始化 searchForm
searchFormConfig.value.forEach((field) => {
    searchForm.value[field.queryAttributName] = '';
});

// 分页相关
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const total = ref<number>(0);

// 是否展开高级查询
const isAdvancedSearch = ref<boolean>(false);
// 控制鼠标悬停状态
const isHovered = ref<boolean>(false);

// 模拟后端数据
const mockApiData = ref<TableData[]>([
    { date: "2023-05-03", name: "Alice", address: "Beijing" },
    { date: "2023-05-04", name: "Bob", address: "Shanghai" },
    { date: "2023-05-05", name: "Charlie", address: "Guangzhou" },
    { date: "2023-05-06", name: "David", address: "Shenzhen" },
    { date: "2023-05-07", name: "Eve", address: "Hangzhou" },
    { date: "2023-05-08", name: "Frank", address: "Chengdu" },
    { date: "2023-05-09", name: "Grace", address: "Wuhan" },
    { date: "2023-05-10", name: "Henry", address: "Xi'an" },
    { date: "2023-05-11", name: "Ivy", address: "Tianjin" },
    { date: "2023-05-12", name: "Jack", address: "Nanjing" },
    { date: "2023-05-07", name: "Eve", address: "Hangzhou" },
    { date: "2023-05-08", name: "Frank", address: "Chengdu" },
    { date: "2023-05-09", name: "Grace", address: "Wuhan" },
    { date: "2023-05-10", name: "Henry", address: "Xi'an" },
    { date: "2023-05-11", name: "Ivy", address: "Tianjin" },
    { date: "2023-05-12", name: "Jack", address: "Nanjing" },
    { date: "2023-05-07", name: "Eve", address: "Hangzhou" },
    { date: "2023-05-08", name: "Frank", address: "Chengdu" },
    { date: "2023-05-09", name: "Grace", address: "Wuhan" },
    { date: "2023-05-10", name: "Henry", address: "Xi'an" },
    { date: "2023-05-11", name: "Ivy", address: "Tianjin" },
    { date: "2023-05-12", name: "Jack", address: "Nanjing" },
]);

// 过滤数据
const fetchData = () => {
    setTimeout(() => {
        let filtered = mockApiData.value.filter((item) => {
            return (
                (!searchForm.value.name || item.name.includes(searchForm.value.name)) &&
                (!searchForm.value.address || item.address.includes(searchForm.value.address)) &&
                (!searchForm.value.date || item.date === searchForm.value.date) &&
                (!searchForm.value.city || item.address === searchForm.value.city)
            );
        });
        total.value = filtered.length;
        const start = (currentPage.value - 1) * pageSize.value;
        tableData.value = filtered.slice(start, start + pageSize.value);
    }, 500);
};

// 查询
const search = () => {
    currentPage.value = 1;
    fetchData();
};

// 重置
const reset = () => {
    Object.keys(searchForm.value).forEach((key) => {
        searchForm.value[key] = '';
    });
    search();
};

// 切换高级查询
const toggleAdvancedSearch = () => {
    isAdvancedSearch.value = !isAdvancedSearch.value;
};

// 表格行样式
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
    return rowIndex % 2 === 1 ? "success-row" : "";
};
</script>

<style scoped>
.content-container {
  display: flex;
  flex-direction: column;
  height: 100%; /* 改为相对高度 */
  background-color: #f4f4f4;
  padding: 0;
  margin: 0;
}

.search-form-wrapper {
  background-color: white;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  flex-shrink: 0; /* 禁止收缩 */
}

.table-container {
  flex: 1;
  overflow-y: auto; /* 允许表格区域滚动 */
  padding: 15px;
  background-color: white;
}

.pagination-wrapper {
  background-color: white;
  padding: 10px;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
  text-align: center;
  flex-shrink: 0; /* 禁止收缩 */
}

.toggle-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409eff;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease-in-out;
}

.toggle-btn.hovered {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
}

::v-deep(.el-table .success-row) {
  background-color: #fdf6ec !important;
}
</style>